package com.jdbctemplate.base;

import com.jdbctemplate.domain.Account;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

/**
 * 单表操作
 */
public class DemoCRUD {
    public static void main(String[] args) {
        ApplicationContext ac=new ClassPathXmlApplicationContext("jdbctem.xml");
        JdbcTemplate jt=ac.getBean("jdbcTemplate", JdbcTemplate.class);
        /*保存
        *update
        * */
       // jt.update("insert into account(name,money) values (?,?)","eee","334f");
        /**
         * 更新
         * update
         */
       // jt.update("update account set name=?,money=? where id=?","ccc",345f,10);
        /**
         * 删除
         * update
         */
        jt.update("delete from account where  id=?",10);
        /*
        查询所有
         */
        //自己写的方式，强大的spring.jdbc也提供的有。
       //List<Account> accounts= jt.query("select * from account", new AccountRowMapper());
        //spring.jdbc提供的需要在beanPropertyRowMapper中的参数要加载字节码文件
        List<Account> accounts= jt.query("select * from account", new BeanPropertyRowMapper<Account>(Account.class));
       for (Account account:accounts){
           System.out.println(account);
       }
        /**
         * 查询一个
         */
        System.out.println("----------------");
        List<Account> accounts1=jt.query("select * from account where id=?",new BeanPropertyRowMapper<Account>(Account.class),12);
        System.out.println(accounts1);
        /**
         * 查询返回一行一列，（使用聚合函数，但是不加group by字句)
         */
        Integer i=jt.queryForObject("select count(*) from account where money>?",Integer.class,1000f);
        System.out.println(i);
    }
}
/**
 * 对应的查询所有的类型，定义account的封装策略
 */
class AccountRowMapper implements RowMapper<Account>{
    /**
     * 结果集数据封装金account中，然后由spring把每个account加到集合中
     * @param rs
     * @param rowNum
     * @return
     * @throws SQLException
     */
    public Account mapRow(ResultSet rs, int rowNum) throws SQLException {
        Account account=new Account();
        account.setId(rs.getInt("id"));
        account.setName(rs.getString("name"));
        account.setMoney(rs.getFloat("money"));
        return account;
    }
}
